<template>
  <a-button v-if="!danger" type="link" :class="['link-button', size, { disabled: disabled }]" :href="href"
    :target="target" :disabled="disabled" :loading="loading" :icon="icon" @click="handleClick">
    <slot>{{ text }}</slot>
  </a-button>
  <template v-else>
    <a-popconfirm :disabled="disabled" :title="tipMsg" :ok-text="okText" :cancel-text="cancelText" :placement="placement" @confirm="confirm"
      @cancel="cancel">
      <a-button type="link" :class="['link-button', size, { danger: danger, disabled: disabled }]" :disabled="disabled"
        :loading="loading" @click="handleClick">
        <slot>{{ text }}</slot>
      </a-button>
    </a-popconfirm>
  </template>
</template>

<script lang="ts" setup>
interface Props {
  /** 按钮文本 */
  text?: string;
  /** 链接地址 */
  href?: string;
  /** 链接打开方式 */
  target?: '_blank' | '_self' | '_parent' | '_top';
  /** 是否禁用 */
  disabled?: boolean;
  /** 是否显示加载状态 */
  loading?: boolean;
  /** 图标 */
  icon?: any;
  /** 按钮大小 */
  size?: 'small' | 'middle' | 'large';
  /** 危险状态 */
  danger?: boolean;
  /** 自定义类名 */
  tipMsg?: string
  okText?: string
  cancelText?: string
  placement?: 'top' | 'bottom' | 'left' | 'right' | 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | 'leftTop' | 'leftBottom' | 'rightTop' | 'rightBottom'
}

const props = withDefaults(defineProps<Props>(), {
  target: '_self',
  size: 'small',
  tipMsg: "确定删除该条数据?",
  okText: "确定",
  cancelText: "取消",
  placement: "top"
});

const emit = defineEmits(['click', 'confirm', 'cancel']);

const handleClick = (e: MouseEvent) => {
  if (props.disabled || props.loading) {
    e.preventDefault();
    return;
  }
  emit('click');
};

const confirm = () => {
  emit("confirm")
}

const cancel = () => {
  emit("cancel")
}

defineOptions({
  name: 'ALink'
})
</script>

<style lang="less" scoped>
@primary-color: #2374ff;
@primary-5: #2374ff;
@primary-7: #2374ff;
@error-color: #ff4d4f;
@error-color-hover: #ff4d4f;
@error-color-active: #ff4d4f;
@disabled-color: #d9d9d9;

.link-button {
  padding: 0;
  height: auto;
  line-height: inherit;
  color: @primary-color;
  text-decoration: none;
  background: transparent;
  border: none;
  box-shadow: none;
  transition: color 0.3s;

  &:hover {
    color: @primary-5;
    text-decoration: underline;
  }

  &:active {
    color: @primary-7;
  }

  &.small {
    font-size: 12px;
  }

  &.middle {
    font-size: 14px;
  }

  &.large {
    font-size: 16px;
  }

  &.danger {
    color: @error-color;

    &:hover {
      color: @error-color-hover;
    }

    &:active {
      color: @error-color-active;
    }
  }

  &.disabled {
    color: @disabled-color;
    cursor: not-allowed;

    &:hover {
      color: @disabled-color;
      text-decoration: none;
    }
  }
}
</style>